﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace MyImage
{
    public class DataAcess
    {
        public static byte[] GetPictureByID(int id)
        {
            try
            {
            int ID=int.Parse(id.ToString());
            SqlConnection connection = new SqlConnection(
                ConfigurationManager.ConnectionStrings["image"].ConnectionString);
            SqlCommand command = new SqlCommand("sp_GetImageByID", connection);
            command.CommandType = CommandType.StoredProcedure;
            // create params
            SqlParameter param = new SqlParameter("@img_pk", SqlDbType.Int);
            param.Value=ID;
            command.Parameters.Add(param);
            connection.Open();

            byte[] imgdata=(byte[])(command.ExecuteScalar());
            connection.Close();
            return imgdata;
            }
            catch(SqlException ex)
            {
                throw new Exception(ex.Message,ex);
            }

                 
        }
        public static int SaveImage(ref int img_id, byte[] imgbin)
        {
            SqlConnection connection = new SqlConnection(
                ConfigurationManager.ConnectionStrings["image"].ConnectionString);
            SqlCommand command = new SqlCommand("sp_AddImage",
                connection);
            command.CommandType = CommandType.StoredProcedure;
            int myID = 0;
            SqlParameter param = new SqlParameter("@img_pk", SqlDbType.Int);
            param.Value = myID;
            command.Parameters.Add(param);
            param.Direction = ParameterDirection.Output;
            SqlParameter param1 = new SqlParameter("@img_data", SqlDbType.Image);
            param1.Value = imgbin;
            command.Parameters.Add(param1);
            connection.Open();
            int numRowsAffected = command.ExecuteNonQuery();
            connection.Close();
            img_id = int.Parse(param.Value.ToString());
            return numRowsAffected;
        }
        public static DataSet GetAllImage()
        {
            SqlConnection connection=new SqlConnection(ConfigurationManager.ConnectionStrings["image"].ConnectionString);
            SqlCommand command = new SqlCommand("sq_GetImages", connection);
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = command;
            DataSet ds = new DataSet();
            da.Fill(ds, "MYIMAGES");
            return ds;
        }
    }
}
